package com.wxw.springcloud.controller;


import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import com.wxw.springcloud.bean.User;
import com.wxw.springcloud.hystrix.MyHystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author wxw
 * @data 2021/1/18 20 :19
 * @description
 */
@RestController
public class WebController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/web/hello")
    public List<User> hello() {
//        业务逻辑。。。

        //调用springcloud提供者提供的服务
        //return restTemplate.getForEntity("http://localhost:8080/hello", String.class).getBody();
        ResponseEntity<List> list = restTemplate.getForEntity("http://01-SPRINGCLOUD-SERVICE-PROVIDER/hello", List.class);
        List<User> body = list.getBody();

        //传递参数
/*        ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();
        map.put("id",1);
        map.put("name","张三");
        ResponseEntity<String> testmap = restTemplate.getForEntity("http://01-SPRINGCLOUD-SERVICE-PROVIDER/hello?id={id}&name={name}", String.class,map);  */

        // POST请求传递参数需要使用此map
      /*  MultiValueMap<String, Object> valueMap = new LinkedMultiValueMap<>();
       restTemplate.postForEntity("http://01-SPRINGCLOUD-SERVICE-PROVIDER/hello", valueMap, String.class);*/
        return body;
    }
    //ignoreExceptions = Exception.classg忽略异常
    @GetMapping("/web/hystrix")
    @HystrixCommand(fallbackMethod="error",ignoreExceptions = Exception.class)
    public String Hystrix() {
//        业务逻辑。。。
        //调用springcloud提供者提供的服务
        return restTemplate.getForEntity("http://01-SPRINGCLOUD-SERVICE-PROVIDER/hystrix", String.class).getBody();

    }
    //Throwable throwable拿到异常信息
    public  String error(Throwable throwable){
        System.out.println(throwable.getMessage());
        return "error";
    }

    @GetMapping("/web/hystrix2")
    public Object Hystrix2() throws ExecutionException, InterruptedException {
//        业务逻辑。。。
        //调用springcloud提供者提供的服务
        MyHystrixCommand myHystrixCommand = new MyHystrixCommand(com.netflix.hystrix.HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("")),restTemplate);
        Object execute = myHystrixCommand.execute();
     /*   //异步调用
        Future queue = myHystrixCommand.queue();
        //业务逻辑。。。调用

        //业务逻辑。。。*/

        return execute;

    }
}

